package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;


    @Override
    public User findByUsername(String username) {

        //查询用户基本信息
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //通过用户id去查询角色信息
        Set<Role> roles = roleDao.findByUserId(userId);
        user.setRoles(roles);
        //遍历角色查询权限
        for (Role role : roles) {
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return user;
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        String queryString = queryPageBean.getQueryString();
        Page<User> page = userDao.findByCondition(queryString);
        long total = page.getTotal();
        List<User> result = page.getResult();
        return new PageResult(total, result);
    }

    @Override
    public void add(Integer[] roleIds, User user) {
        //添加用户基本信息
        //调用springsecurity框架对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.add(user);
        //建立用户和角色表关系
        Integer userId = user.getId();
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map map = new HashMap<>();
                map.put("role_id", roleId);
                map.put("user_id", userId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public void deleteByUserId(Integer id) {
        //查询关系表
        Integer count = userDao.findCountByUserId(id);
        if (count > 0) {
            new RuntimeException();
        }
        userDao.deleteByUserId(id);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {

        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        userDao.edit(user);
        Integer userId = user.getId();
        //删除原有表关系
        userDao.deleteAssociation(userId);
        //建立新的表关系
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map map = new HashMap<>();
                map.put("role_id", roleId);
                map.put("user_id", userId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public List<Map> getMenuByUsername(String username) {
     /*   User user = userDao.findByUsername(username);
        //通过用户id查询该用户拥有的所有角色信息
        Integer userId = user.getId();
        List<Role> rolesList = userDao.findRolesByUserId(userId);
        //主菜单
        List<Map> menus=null;
        //遍历角色查询其拥有菜单信息
        for (Role role : rolesList) {
            Integer roleId = role.getId();
            menus = roleDao.findMenuByRoleId(roleId);
        }*//*
        return menus;*/
        return null;
    }


    @Override
    public List<Map> getMenuByUsername2(String username) {
        User user = userDao.findByUsername(username);
        //获取当前用户对应所有角色的菜单集合(注意去重)
        List<Menu> list = roleDao.findMenuByUserId(user.getId());

        List<Map> userMenu = new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getParentMenuId() == null) {
                Map map = new HashMap();
                List<Map> childern = new ArrayList<>();
                for (Menu menu1 : list) {
                    if (menu1.getParentMenuId() == menu.getId()) {
                        Map map1 = new HashMap();
                        String linkUrl = menu1.getLinkUrl();
                        String path = menu1.getPath();
                        String tittle = menu1.getName();
                        map1.put("linkUrl", linkUrl);
                        map1.put("path", path);
                        map1.put("name", tittle);
                        map1.put("level", menu1.getLevel());
                        map1.put("parentMenuId", menu1.getId());
                        map1.put("id", menu1.getId());
                        childern.add(map1);
                    }
                }
                String linkUrl = menu.getLinkUrl();
                String path = menu.getPath();
                String tittle = menu.getName();
                map.put("linkUrl", linkUrl);
                map.put("path", path);
                map.put("name", tittle);
                map.put("level", menu.getLevel());
                map.put("parentMenuId", menu.getId());
                map.put("id", menu.getId());
                map.put("children", childern);
                map.put("icon", menu.getIcon());
                userMenu.add(map);
            }

        }
        return userMenu;
    }
}
